﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace EasyDLL
{
    public class StringWrapper
    {
        /// <summary>
        /// 从给定字符串中寻找给定的前后tag之间的集合（用例：网页抽取特定部分）
        /// </summary>
        /// <param name="start">开始tag</param>
        /// <param name="end">结束tag</param>
        /// <param name="content">content</param>
        /// <returns></returns>
        public List<string> GetMiddleStrings(string start, string end, string content)
        {
            List<string> list = new List<string>();
            try
            {
                string pattern = string.Format("{0}(?<g>(.|[\r\n])+?){1}", start, end);//匹配URL的模式,并分组    //理解这个正则
                MatchCollection mc = Regex.Matches(content, pattern);//满足pattern的匹配集合
                if (mc.Count != 0)
                {
                    foreach (Match match in mc)
                    {
                        GroupCollection gc = match.Groups;
                        list.Add(gc["g"].Value);
                    }
                }
            }
            catch (Exception e)
            {
                throw new InvalidOperationException();
            }
            return list;
        }

        /// <summary>
        /// 得到字符串中包含指定字符串的个数
        /// </summary>
        /// <param name="content">要检索的字符串</param>
        /// <param name="containsStr">包含的字符串</param>
        /// <returns></returns>
        public int GetContainsCount(string content,string containsStr)
        {
            int res = 0;
            int indexOf = 0;
            while (indexOf <= content.Length)
            {
                indexOf = content.IndexOf(containsStr,indexOf);
                if(indexOf >= 0)
                {
                    res++;
                    indexOf += containsStr.Length; 
                    //实际找到的是第一个字符而已，所以这边
                    //向后移动的时候要多移动containsStr位
                }
                else
                {
                    break;
                }
            }
            return res;
        }
    }
}
